package com.trade.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.trade.model.Contact;
import com.trade.model.Customer;
import com.trade.model.Goods;
import com.trade.model.Role;
import com.trade.model.SaleOrder;
import com.trade.model.User;
import com.trade.service.IContactService;
import com.trade.service.ICustomerService;
import com.trade.service.IGoodsService;
import com.trade.service.ISaleOrderService;
import com.trade.service.IUserService;

public class ContactAction extends DispatchAction {
	private static Log logger = LogFactory.getLog(GoodsAction.class);
	private static	SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
	private IUserService userService;
	private IContactService contactService;
	private IGoodsService goodsService;
	private ICustomerService customerService;
	private ISaleOrderService saleOrderService;
	
	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	
	public IContactService getContactService() {
		return contactService;
	}

	public void setContactService(IContactService contactService) {
		this.contactService = contactService;
	}
	
	public IGoodsService getGoodsService() {
		return goodsService;
	}

	public void setGoodsService(IGoodsService goodsService) {
		this.goodsService = goodsService;
	}
	
	public ICustomerService getCustomerService() {
		return customerService;
	}

	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}
	
	public ISaleOrderService getSaleOrderService() {
		return saleOrderService;
	}

	public void setSaleOrderService(ISaleOrderService saleOrderService) {
		this.saleOrderService = saleOrderService;
	}

	public ActionForward input(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<User> users = userService.getAllUsers();
		request.setAttribute("users", users);
		List<Goods> goodses = goodsService.getAllGoods();
		request.setAttribute("goodses", goodses);
		List<Customer> customers = customerService.getAllCustomerUsers();
		request.setAttribute("customers", customers);
		return mapping.findForward("input");
    }
	
	public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		User loginUser = (User)request.getSession().getAttribute("loginUser");
		String roleName = loginUser.getRole().getName();
		List<Contact> contacts = null;
		if (roleName.equalsIgnoreCase(Role.ROLE_SALE_MANAGER)) {
			contacts = contactService.getAllContacts(Contact.TOTAL_LIMIT_MANAGER, false);
		} else if (roleName.equalsIgnoreCase(Role.ROLE_MANAGER)) {
			contacts = contactService.getAllContacts(Contact.TOTAL_LIMIT_MANAGER, true);
		} else {
			request.setAttribute("nopermission", true);
		}
		request.setAttribute("contacts", contacts);
		return mapping.findForward("list");
    }
	
	public ActionForward getSaleOrdersByContactId(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String contactStr = request.getParameter("contactId");
		Contact contact = this.contactService.getContactById(Long.valueOf(contactStr));
		request.setAttribute("saleOrders", contact.getSaleOrders());
		return mapping.findForward("orderlist");
    }
	
	public ActionForward changeState(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String idStr = request.getParameter("id");
		String stateStr = request.getParameter("state");
		Contact contact = this.contactService.getContactById(Long.valueOf(idStr));
		contact.setState(Integer.valueOf(stateStr));
		if (contact.getState() == Contact.STATE_APPROVE) {
			contact.setApprover((User)request.getSession().getAttribute("loginUser"));
		}
		this.contactService.save(contact);
		return list(mapping, form, request, response);
    }
	
	public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		String customerId = request.getParameter("customerid");
		Contact newContact = new Contact();
		newContact.setTitle(title);
		newContact.setContent(content);
		User creator = (User)request.getSession().getAttribute("loginUser");
		newContact.setCreator(creator);
		Customer customer = customerService.GetCustomerById(customerId);
		newContact.setCustomer(customer);
		newContact.setContactTime(formatDate.parse(formatDate.format(new Date())));
		
		try {
			this.contactService.save(newContact);
			int orderNum = Integer.valueOf(request.getParameter("orderNum"));
			if (orderNum > 0) {
				for (int i = 0; i < orderNum; i++) {
					String goodsIdStr = request.getParameter("goodsId" + i);
					String priceStri = request.getParameter("price" + i);
					String sellNum = request.getParameter("num" + i);
					String outStoreTimeStr = request.getParameter("outStoreTime" + i);
					String inspectoridStr = request.getParameter("inspectorid" + i);
					Goods goods = goodsService.getGoods(Long.valueOf(goodsIdStr));
					User inspector = userService.getUserByUserID(inspectoridStr);
					SaleOrder order = new SaleOrder();
					order.setContact(newContact);
					order.setCustomer(customer);
					order.setGoods(goods);
					order.setInspector(inspector);
					order.setOutStoreTime(formatDate.parse(outStoreTimeStr));
					order.setSalesNumber(Integer.valueOf(sellNum));
					order.setSellPrice(Double.valueOf(priceStri));
					saleOrderService.save(order);
					newContact.setTotal(newContact.getTotal() + (long)(order.getSalesNumber() * order.getSellPrice()));
					newContact.getSaleOrders().add(order);
				}
			}
			this.contactService.save(newContact);
			return mapping.findForward("success");
		} catch (Exception e) {
			request.setAttribute("message", "合同保存失败");
			return mapping.findForward("input");
		}
		
    }
}
